'use strict';

const Service = require('egg').Service;
const jwt = require('jsonwebtoken');

class UsersService extends Service {
  // 1. Cookie 验证
  async cookieOfLogin({ data }) {
    const { ctx } = this;

    // 创建查询
    const sqlQuery = { where: data };
    const user = await ctx.model.Users.findOne(sqlQuery);

    if (user) {
      ctx.cookies.set('user', JSON.stringify(user), {
        maxAge: 24 * 3600 * 1000, // 有效期，单位：毫秒
        httpOnly: true, // 是否只能通过 HTTP 请求访问 cookie
        secure: true, // 是否前端可编辑
      });

      return {
        code: 200,
        message: 'cookie 鉴权成功',
      };
    }

    return {
      code: 5004,
      message: '鉴权错误',
    };
  }

  async login({ data }) {
    const { ctx } = this;
    const config = ctx.app.config;

    const secretKey = config.authToken.secretKey;

    // 创建查询
    const sqlQuery = { where: data };
    const user = await ctx.model.Users.findOne(sqlQuery);

    // TODO: 执行错误会进行删除 model ? 错误没有捕获的原因？

    if (user) {
      const payload = { uid: user.id, account: user.account };
      const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
      return {
        token,
      };
    }
    return {
      token: '',
      code: 5004,
      message: 'token 获取错误',
    };
  }
}

module.exports = UsersService;
